package com.gy.config;

import com.gy.pojo.User;
import com.gy.service.UserService;
import com.gy.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//第二步 自定义的UserRealm
//继承AuthorizingRealm  重写它的两个方法（授权和认证）
public class UserRealm extends AuthorizingRealm {

    //将数据库拿过来
    @Autowired
    UserServiceImpl userService;

    //授权   给用户授于一些权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了====授权方法doGetAuthorizationInfo");
        //SimpleAuthenticationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        //强转成User
        User currentUser = (User) subject.getPrincipal();//拿到User对象 了
        //设置当前用户的权限  一定要修改返回值

/*        if (currentUser.getPerm() != null) {
            info.addStringPermission(currentUser.getPerm());
            return info;
        } else {
            return null;
        }*/


        //加一个超级用户
        //注意数据库perm这个属性一定不能为空
        if (currentUser.getPerm().equals("super")) {

            info.addStringPermission("user:admin");
            info.addStringPermission("user:work");
            return info;
        } else{
            info.addStringPermission(currentUser.getPerm());
            return info;

        }

    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("执行了====认证方法doGetAuthenticationInfo");


        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //连接真实的数据库
        User user=userService.selectUserById(userToken.getUsername());

        if(user==null){//没有这个人
            return null;//UnknownAccountException
        }

        //密码认证，shiro做
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }

}
